<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
    <title>Upload Disk Image</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

</head>
<body>
<div class="container">
    <div class="section">
        <div class="row">
            <div class="col m6 push-m2" id="main-panel">
              <div class="row">
                  <div class="input-field col m4">
                      <input id="image_name" placeholder="input image name" type="text" class="validate" name="name" required>
                      <label for="image_name" id="name-label"></label>
                  </div>
              </div>
              <div class="row">
                  <div class="input-field col m8">
                      <textarea id="description" placeholder="descript this image" class="materialize-textarea" required></textarea>
                      <label for="description" id="description-label"></label>
                  </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="tag-label"></label>
                </div>
              </div>
              <div class="row">
                  <div class="col m8">
                    <div class="row" id="tag-list">
                    </div>
                  </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="file-label"></label>
                </div>
              </div>
              <div class="row">
                <form action="" method="post" enctype="multipart/form-data" id="upload_form">
                  <div class="file-field input-field col m12">
                    <div class="row">
                      <div class="file-path-wrapper col m10">
                        <input class="file-path validate" type="text" placeholder="choose upload file" required>
                      </div>
                      <div class="waves-effect waves-light blue-grey lighten-2 btn-small col m2">
                        <span id="select-label">
                        </span>
                        <input type="file" name="image">
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
        </div>
    </div>
    <div class="divider"></div>
    <div class="section">
        <div class="row">
            <div class="col m2">
                <a class="waves-effect waves-light blue-grey lighten-2 btn" onclick="window.history.back()" id="back-caption"><i
                        class="material-icons left">chevron_left</i></a>
            </div>
            <div class="col m2 right" id="button">
                <button class="waves-effect waves-light blue-grey lighten-2 btn" onclick="uploadImage()" id="upload-caption">
                    <i class="material-icons right">file_upload</i>
                </button>
            </div>
        </div>
    </div>
</div>

<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script>

var texts = N.GetTexts();

$(function(){
  N.ValidateSession();
  $('#back-caption').append(texts.get(N.TagBack));
  $('#upload-caption').prepend(texts.get(N.TagUpload));

  $('#name-label').text(texts.get(N.TagImageName));
  $('#description-label').text(texts.get(N.TagDescription));
  $('#tag-label').text(texts.get(N.TagTag));
  $('#file-label').text(texts.get(N.TagImageFile));
  $('#select-label').text(texts.get(N.TagSelect));

  //add tags
  var tagList = $('#tag-list');
  N.GetAllImageTags().forEach((tag)=>{
    tagList.append(
      $('<div>').addClass('col m3').append(
        $('<label>').append(
          $('<input>').attr('type', 'checkbox').attr('name', 'tag').val(tag[0])
        ).append(
          $('<span>').text(tag[1])
        )
      )
    );
  });

  M.AutoInit();
});

function uploadImage(){
  var imageName = $('#image_name').val();
  if (!imageName){
    M.toast({html: 'invalid image name'});
    return;
  }
  var imageDescription = $('#description').val();
  if (!imageDescription){
    M.toast({html: 'input image description'});
    return;
  }

  var tags = new Array();
  $("input[name='tag']:checkbox:checked").each(function(){
    tags.push($(this).val());
  });
  createImage(imageName, imageDescription, tags);
}

function releaseImage(id){
  $.ajax({
      url:'/disk_images/' + id,
      type: "DELETE",
      success: function (result) {
          if (0 != result['error_code']) {
              M.toast({html: 'release image fail: ' + result['message'], outDuration: 600});
              return;
          }
          M.toast({html: 'disk image "' + id + '" released'})
          setTimeout(refresh, 1500);
      }
  });
}

function createImage(name, description, tags){
  var request = new Object();
  request.name = name;
  request.description = description;
  request.owner = N.GetCurrentUser();
  request.group = N.GetCurrentGroup();
  request.tags = tags;
  $.post(
    '/disk_images/',
    JSON.stringify(request),
    function(result){
      if (0 != result['error_code']) {
          M.toast({html: 'create disk image fail: ' + result['message'], outDuration: 600});
          return;
      }
      var imageId = result['data']['id'];
      startTransport(name, description, tags, imageId);
    },
    "json"
  )
}

function startTransport(name, description, tags, imageId){
  var form = $('#upload_form');
  form.attr('action', '/disk_image_files/' + imageId);
  form.ajaxForm({
    beforeSend: function(){
      $('#button').empty();
      $('#main-panel').empty();
      var table = $('<table>').addClass('striped');
      table.append(
        $('<tr>').append(
          $('<td>').text(texts.get(N.TagName))
        ).append(
          $('<td>').text(name)
        )
      ).append(
        $('<tr>').append(
          $('<td>').text(texts.get(N.TagDescription))
        ).append(
          $('<td>').text(description)
        )
      ).append(
        $('<tr>').append(
          $('<td>').text(texts.get(N.TagTag))
        ).append(
          $('<td>').text(tags.join('/'))
        )
      ).append(
        $('<tr>').append(
          $('<td>').text('ID')
        ).append(
          $('<td>').text(imageId)
        )
      ).append(
        $('<tr>').append(
          $('<td>').text(texts.get(N.TagResult))
        ).append(
          $('<td>').attr('id', 'operate_result').append(
            $('<div>').addClass('center').append(
              $('<span>').text('Uploading... 0%').attr('id', 'progress-info')
            )
          ).append(
            $('<div>').addClass('progress').append(
              $('<div>').addClass('determinate').width('0%').attr('id', 'progress-bar')
            )
          )
        )
      );
      $('#main-panel').append(table);
    },
    uploadProgress: function(event, position, total, percentComplete) {
      var progress = percentComplete + '%';
      $('#progress-bar').width(progress);
      $('#progress-info').text('Uploading... ' + progress);
    },
    success: function() {
      $('#operate_result').text('success');
      $('#button').append(
        $('<a>').attr('href', '/images.html').append(
          $('<button>').addClass('waves-effect waves-light blue-grey lighten-2 btn').text(texts.get(N.TagFinish)).prepend(
            $('<i>').addClass('material-icons').text('check')
          )
        )
      );
      N.WriteOperateLog('upload disk image ' + name + ' / ' + imageId);
    },
    error: function(jqXHR, textStatus, errorThrown){
      releaseImage(imageId);
      $('#operate_result').text(errorThrown);
    }
  });
  form.submit();
}

</script>
</body>
</html>
